#! /usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
@File:      tc_ag_util-linux_hwclock_fun_004.py
@Time:      2022/8/31 10:06:45
@Author:    yangshunfeng.ysf
@Version:   1.0
@Contact:   lyq01395646@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    liuyaqing
"""
from common.basetest import RemoteTest
import datetime
import ntplib

class DateTest(RemoteTest):
    PARAM_DIC = {"pkg_name": "systemd"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)

    def test_systime(self):
        """
        See  tc_ag_util-linux_hwclock_fun_004.yaml for details
        :avocado: tags=P1,noarch,remote,container_func,vhd_img,baseos_container_default
        """
        timegap=60
        client = ntplib.NTPClient()
        try:
            response = client.request('ntp.aliyun.com')
            t1 = datetime.datetime.fromtimestamp(response.tx_time)
        except Exception as e:
            print("Error occurred, use datetime.datetime.now()", e)
            t1 = datetime.datetime.now()
        ret_c,localtime = self.cmd("date +'%s'",container_flag=1)
        localtime = int(localtime)
        t2 = datetime.datetime.fromtimestamp(localtime)
        self.log.debug("t1 represents the precise time obtained from the ntp server: %s", t1)
        self.log.debug("t2 indicates the current time of the test machine: %s", t2)
        td1 = t2 - t1
        self.assertTrue(abs(td1.total_seconds()) < timegap,"timegap between t1 and t2 over 60s")
        if self.container_id == None:
            ret_c, hwtime = self.cmd("hwclock -s && date +'%s'")
            hwtime = int(hwtime)
            t3 = datetime.datetime.fromtimestamp(hwtime)
            self.cmd('systemctl restart chronyd')
            self.cmd('chronyc sources -v')
            self.log.debug("t3 indicates the hardware time of the test machine: %s", t3)
            td2 = t3 - t1
            self.assertTrue(abs(td2.total_seconds()) < timegap,"timegap between t1 and t3 over 60s")

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)